package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.dto.UserQuery;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleRepairQuery;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.entity.VehicleRepair;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleRepairVO;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.mapper.VehicleRepairMapper;

import cn.tedu.ivos.vehicle.service.VehicleRepairService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class VehicleRepairServiceImpl implements VehicleRepairService {
    @Autowired
    VehicleRepairMapper vehicleRepairMapper;
    @Autowired
    VehicleMapper vehicleMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public List<VehicleRepairVO> selectForm(VehicleRepairQuery vehicleRepairQuery) {
        log.debug("vehicleRepairQuery = " + vehicleRepairQuery);
        VehicleQuery vehicleQuery = new VehicleQuery();

        List<VehicleRepairVO> list = vehicleRepairMapper.select(vehicleRepairQuery);
        for (VehicleRepairVO vehicleRepairVO : list) {
            vehicleQuery.setId(vehicleRepairVO.getVehicleId());
            List<VehicleVO> vos = vehicleMapper.selectVehicle(vehicleQuery);
            for (VehicleVO vehicleVO : vos) {
                vehicleRepairVO.setLicense(vehicleVO.getLicense());
            }
        }
        return list;

    }

    @Override
    public List<VehicleVO> selectLicense() {
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setStatus("1");
        return vehicleMapper.selectVehicle(vehicleQuery);

    }

    @Override
    public void insertForm(VehicleRepair vehicleRepair) {
        Vehicle vehicle = new Vehicle();
        UserQuery userQuery = new UserQuery();

        if (vehicleRepair.getStatus().equals("1")){
            vehicle.setStatus("3");//设置车辆的状态为维修中
        }else {
            vehicle.setStatus("1");//设置车辆的状态为空闲
        }
        vehicle.setId(vehicleRepair.getVehicleId());
        vehicleMapper.update(vehicle);

        userQuery.setUsername(vehicleRepair.getUsername());
        List<UserVO> list = userMapper.selectUser(userQuery);
        for (UserVO userVO : list) {
            vehicleRepair.setUserId(userVO.getId());
        }

        if (vehicleRepair.getId()==null){//新增维修车辆
            vehicleRepairMapper.insertForm(vehicleRepair);
        }else {//更新维修车辆
            vehicleRepairMapper.updateForm(vehicleRepair);
        }
    }

    @Override
    public void delete(Long id) {
        vehicleRepairMapper.delete(id);
    }

}
